package com.xm.handler;


import com.xm.exception.BaseException;
import com.xm.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandlersss {


//    /**
//     * 捕获请求参数缺失异常
//     * @param ex
//     * @return
//     */
//
//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    public Result exceptionHandler(HttpMessageNotReadableException ex){
//        log.error("异常信息：{}", ex.getMessage());
//
//        return Result.error("请求参数缺失");
//    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result customException(BaseException e) {
        log.error("业务异常:{},异常时间:{}",e.getMessage(), LocalDateTime.now());
        e.printStackTrace();
        return Result.error(e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exception(Exception e) {
        log.error("系统出现异常:{},异常时间:{}", e.getMessage(), LocalDateTime.now());
        e.printStackTrace();
        return  Result.error("执行过程异常, 请重试");
    }

    /**
     * JSR303校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> msgList = new ArrayList<>();
        // 将获取的错误信息放入集合中
        bindingResult.getFieldErrors().stream().forEach(item ->msgList.add(item.getDefaultMessage()));
        // 拼接错误信息
        String msg = StringUtils.join(msgList, ',');
        log.error("客户端传参出现异常:{},异常时间:{}", msg, LocalDateTime.now());
        return  Result.error(msg);
    }


}
